package com.project.school_flate.serviceimpl.shop;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.project.school_flate.dto.shop.ShopInfoDto;
import com.project.school_flate.entity.order.table.OrderTakeawayTableDef;
import com.project.school_flate.entity.shop.ShopInfo;
import com.project.school_flate.entity.shop.table.ShopInfoTableDef;
import com.project.school_flate.entity.table.shop.ShopInfoTable;
import com.project.school_flate.entity.user.UserInfo;
import com.project.school_flate.mapper.order.OrderTakeawayMapper;
import com.project.school_flate.mapper.shop.ShopExamineMapper;
import com.project.school_flate.mapper.shop.ShopInfoMapper;
import com.project.school_flate.mapper.shop.ShopSaveUserMapper;
import com.project.school_flate.service.shop.ShopInfoService;
import com.project.school_flate.util.DateUtils;
import com.project.school_flate.util.PoToDTO;
import com.project.school_flate.util.Result.Result;
import com.project.school_flate.util.system.ComVariableUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  服务层实现。
 *
 * @author 马维健
 * @since 2024/1/2
 */
@Service
public class ShopInfoServiceImpl extends ServiceImpl<ShopInfoMapper, ShopInfo> implements ShopInfoService {

    @Autowired
    private ShopInfoMapper oShopInfoMapper;

    @Autowired
    private ShopExamineMapper oShopExamineMapper;

    @Autowired
    private ShopSaveUserMapper oShopSaveUserMapper;

    @Autowired
    private OrderTakeawayMapper oOrderTakeawayMapper;

    /**
     * 获取店铺
     * @param oShopInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getShopInfo(ShopInfoDto oShopInfoDto) throws Exception {
        List<ShopInfo> oShopInfoList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        //判断是否传入店铺ID
        if(StringUtils.isNotBlank(oShopInfoDto.getId())){
            queryWrapper.where(ShopInfoTable.SHOP_INFO.ID.eq(oShopInfoDto.getId()));
        }
        //判断是否传入店铺名
        if(StringUtils.isNotBlank(oShopInfoDto.getName())){
            queryWrapper.where(ShopInfoTable.SHOP_INFO.NAME.like(oShopInfoDto.getName()));
        }
        //判断是否传入入驻校区ID
        if(StringUtils.isNotBlank(oShopInfoDto.getSchoolId())){
            queryWrapper.where(ShopInfoTable.SHOP_INFO.SCHOOL_ID.eq(oShopInfoDto.getSchoolId()));
        }
        //判断是否传入店铺账号ID
        if(StringUtils.isNotBlank(oShopInfoDto.getAccountId())){
            queryWrapper.where(ShopInfoTable.SHOP_INFO.ACCOUNT_ID.eq(oShopInfoDto.getAccountId()));
        }
        queryWrapper.where(ShopInfoTable.SHOP_INFO.STATE.eq(1));
        queryWrapper.orderBy("create_time desc");
        //是否分页
        if(oShopInfoDto.getPage() != null && oShopInfoDto.getLimit() != null){
            Page<ShopInfo> ShopInfoPage = oShopInfoMapper.paginateWithRelations(oShopInfoDto.getPage(),oShopInfoDto.getLimit(),queryWrapper);
            oShopInfoList = ShopInfoPage.getRecords();
            total = ShopInfoPage.getTotalRow();
        }else{
            oShopInfoList = oShopInfoMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oShopInfoList.size();
        }
        //PoToDto
        List<ShopInfoDto> oShopInfoDtoList = (List<ShopInfoDto>) PoToDTO.poToDtoList(oShopInfoList,new ShopInfoDto());
        oShopInfoDtoList.forEach(item->{
            //判断是否前往完善信息
            if(item.getExamineState() == 1 && item.getIsPerfect() == 0){
                item.setIsGoPerfect(true);
            }
        });
        return Result.ok(oShopInfoDtoList,total);
    }

    /**
     * 添加店铺
     * @param oShopInfoDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result addShopInfo(ShopInfoDto oShopInfoDto) throws Exception {
        ShopInfo oShopInfo = new ShopInfo();
        PoToDTO.poToDto(oShopInfoDto,oShopInfo);
        if(oShopInfoMapper.insert(oShopInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加店铺失败");
        }
        return Result.ok("添加店铺成功");
    }

    /**
     * 修改店铺
     * @param oShopInfoDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result updateShopInfo(ShopInfoDto oShopInfoDto) throws Exception {
        ShopInfo oShopInfo = new ShopInfo();
        PoToDTO.poToDto(oShopInfoDto,oShopInfo);
        oShopInfo.setIsPerfect(1);
        if(oShopInfoMapper.update(oShopInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("修改店铺失败");
        }
        return Result.ok(oShopInfo);
    }

    /**
     * 冻结店铺
     * @param oShopInfoDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result freezeShopInfo(ShopInfoDto oShopInfoDto) throws Exception {
        ShopInfo oShopInfo = new ShopInfo();
        PoToDTO.poToDto(oShopInfoDto,oShopInfo);
        //判断店铺是否还有订单未完成
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.SHOP_ID.eq(oShopInfo.getId()));
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.PAY_STATE.notIn(2,4,6));
        if(CollectionUtils.isNotEmpty(oOrderTakeawayMapper.selectListByQuery(queryWrapper))){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("店铺还有未完成的订单");
        }
        oShopInfo.setState(0);
        if(oShopInfoMapper.update(oShopInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("冻结店铺失败");
        }
        return Result.ok("冻结店铺成功");
    }

    /**
     * 获取店铺（后台）
     * @param oShopInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getShopInfoBack(ShopInfoDto oShopInfoDto) throws Exception {
        List<ShopInfo> oShopInfoList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderBy("create_time desc");
        //是否分页
        if(oShopInfoDto.getPage() != null && oShopInfoDto.getLimit() != null){
            Page<ShopInfo> ShopInfoPage = oShopInfoMapper.paginateWithRelations(oShopInfoDto.getPage(),oShopInfoDto.getLimit(),queryWrapper);
            oShopInfoList = ShopInfoPage.getRecords();
            total = ShopInfoPage.getTotalRow();
        }else{
            oShopInfoList = oShopInfoMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oShopInfoList.size();
        }
        //PoToDto
        List<ShopInfoDto> oShopInfoDtoList = (List<ShopInfoDto>) PoToDTO.poToDtoList(oShopInfoList,new ShopInfoDto());
        return Result.ok(oShopInfoDtoList,total);
    }

    /**
     * 解冻店铺
     * @param oShopInfoDto
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public Result thawShopInfo(ShopInfoDto oShopInfoDto) throws Exception {
        ShopInfo oShopInfo = new ShopInfo();
        PoToDTO.poToDto(oShopInfoDto,oShopInfo);
        oShopInfo.setState(1);
        if(oShopInfoMapper.update(oShopInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("解冻店铺失败");
        }
        return Result.ok("解冻店铺成功");
    }

    /**
     * 获取店铺（客户）
     * @param oShopInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getShopInfoUser(ShopInfoDto oShopInfoDto) throws Exception {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ShopInfoTable.SHOP_INFO.STATE.eq(1));
        queryWrapper.where(ShopInfoTable.SHOP_INFO.EXAMINE_STATE.eq(1));
        queryWrapper.where(ShopInfoTable.SHOP_INFO.IS_PERFECT.eq(1));
        //判断是否传入校园ID
        if(StringUtils.isNotBlank(oShopInfoDto.getSchoolId())){
            queryWrapper.where(ShopInfoTable.SHOP_INFO.SCHOOL_ID.eq(oShopInfoDto.getSchoolId()));
        }
        //判断是否传入名称
        if(StringUtils.isNotBlank(oShopInfoDto.getName())){
            queryWrapper.where(ShopInfoTable.SHOP_INFO.NAME.like(oShopInfoDto.getName()));
        }
        //判断是否传入店铺ID
        if(StringUtils.isNotBlank(oShopInfoDto.getId())){
            queryWrapper.where(ShopInfoTable.SHOP_INFO.ID.eq(oShopInfoDto.getId()));
        }
        //判断是否传入类型
        if(StringUtils.isNotBlank(oShopInfoDto.getShopTypeId())){
            queryWrapper.where(ShopInfoTable.SHOP_INFO.SHOP_TYPE_ID.like(oShopInfoDto.getShopTypeId()));
        }
        queryWrapper.orderBy("name desc");
        List<ShopInfo> oShopInfoList = oShopInfoMapper.selectListWithRelationsByQuery(queryWrapper);
        //PoToDto
        List<ShopInfoDto> oShopInfoDtoList = (List<ShopInfoDto>) PoToDTO.poToDtoList(oShopInfoList,new ShopInfoDto());
        List<ShopInfoDto> oShopInfoDtoPageList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(oShopInfoDtoList)){
//            //获取用户的储蓄店铺ID集合
//            List<String> oShopSaveUserShopIdList = new ArrayList<>();
//            //获取当前用户
//            UserInfo oUserInfo = new UserInfo();
//            if(StpUtil.isLogin()){
//                oUserInfo = (UserInfo) StpUtil.getSession().get("userInfo");
//                if(oUserInfo != null && StringUtils.isNotBlank(oUserInfo.getId())) {
//                    //获取用户的储蓄店铺
//                    queryWrapper = new QueryWrapper();
//                    queryWrapper.where(ShopSaveUserTable.SHOP_SAVE_USER.USER_ID.eq(oUserInfo.getId()));
//                    List<ShopSaveUser> oShopSaveUserList = oShopSaveUserMapper.selectListByQuery(queryWrapper);
//                    if(CollectionUtil.isNotEmpty(oShopSaveUserList)){
//                        //获取用户的储蓄店铺ID集合
//                        oShopSaveUserList.forEach(item->{
//                            oShopSaveUserShopIdList.add(item.getShopId());
//                        });
//                        //判断用户是否有此店铺储蓄
//                        oShopInfoDtoList.forEach(item->{
//                            if(oShopSaveUserShopIdList.contains(item.getId())){
//                                item.setIsUserSave(true);
//                            }
//                        });
//                    }
//                }
//            }
            //获取平台配送费
            Double deliveryPrice = Double.valueOf(ComVariableUtil.getSystemValue("delivery_price"));
            //获取平台打包费
            Double packingCharge = Double.valueOf(ComVariableUtil.getSystemValue("packing_charge"));
            //获取符合营业小时、在营业的店铺
            List<ShopInfoDto> conformList = new ArrayList<>();
            List<ShopInfoDto> noConformList = new ArrayList<>();
            //获取当前小时
            Date nowHour = new Date();
            try {
                nowHour = DateUtils.stringTurnDate("1970-01-01 " + new SimpleDateFormat("HH:mm:ss").format(new Date()),"yyyy-MM-dd HH:mm:ss");
            } catch (Exception e) {
                e.printStackTrace();
            }
            for(ShopInfoDto shopInfoDto : oShopInfoDtoList){
                //默认配送费打包费
                if(shopInfoDto.getDeliveryPrice() == null){
                    shopInfoDto.setDeliveryPrice(deliveryPrice);
                }
                if(shopInfoDto.getPackingCharge() == null){
                    shopInfoDto.setPackingCharge(packingCharge);
                }
                if(DateUtils.checkTwoDate(shopInfoDto.getTradeBeginHour(),nowHour) && DateUtils.checkTwoDate(nowHour,shopInfoDto.getTradeEndHour()) && shopInfoDto.getIsTrade() == 1){
                    conformList.add(shopInfoDto);
                }else{
                    noConformList.add(shopInfoDto);
                }

            }
            //合并
            conformList.addAll(noConformList);
            //手动分页
            if(oShopInfoDto.getPage() != null && oShopInfoDto.getLimit() != null){
                Integer page = oShopInfoDto.getPage();
                Integer limit = oShopInfoDto.getLimit();
                page = (page - 1) * limit;
                if(limit.compareTo(conformList.size()) > 0){
                    limit = conformList.size();
                }
                for(int i = page; i < page + limit; i++){
                    if(i<conformList.size()){
                        oShopInfoDtoPageList.add(conformList.get(i));
                    }
                }
            }else{
                oShopInfoDtoPageList.addAll(conformList);
            }
        }
        return Result.ok(oShopInfoDtoPageList,oShopInfoDtoList.size());
    }

    /**
     * 店铺申请储蓄
     * @param oShopInfoDto
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public Result applyShopInfoSave(ShopInfoDto oShopInfoDto) throws Exception {
        ShopInfo oShopInfo = new ShopInfo();
        PoToDTO.poToDto(oShopInfoDto,oShopInfo);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ShopInfoTableDef.SHOP_INFO.ID.eq(oShopInfo.getId()));
        queryWrapper.where(ShopInfoTableDef.SHOP_INFO.STATE.eq(1));
        ShopInfo oldShopInfo = oShopInfoMapper.selectOneByQuery(queryWrapper);
        if(oldShopInfo == null){
            return Result.error("店铺不存在");
        }
        oShopInfo.setSaveExamineState(2);
        if(oShopInfoMapper.update(oShopInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("店铺申请储蓄失败");
        }
        return Result.ok();
    }

    /**
     * 审核申请储蓄
     * @param oShopInfoDto
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public Result examineShopInfoSave(ShopInfoDto oShopInfoDto) throws Exception {
        ShopInfo oShopInfo = new ShopInfo();
        PoToDTO.poToDto(oShopInfoDto,oShopInfo);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ShopInfoTableDef.SHOP_INFO.ID.eq(oShopInfo.getId()));
        queryWrapper.where(ShopInfoTableDef.SHOP_INFO.STATE.eq(1));
        ShopInfo oldShopInfo = oShopInfoMapper.selectOneByQuery(queryWrapper);
        if(oldShopInfo == null){
            return Result.error("店铺不存在");
        }
        if(oShopInfo.getSaveExamineState() == 1){
            oShopInfo.setIsOpenSave(1);
        }
        if(oShopInfoMapper.update(oShopInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("审核申请储蓄失败");
        }
        return Result.ok();
    }

    /**
     * 获取用户是否是店铺新人
     * @param oShopInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getShopInfoUserNew(ShopInfoDto oShopInfoDto) throws Exception {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ShopInfoTableDef.SHOP_INFO.ID.eq(oShopInfoDto.getId()));
        queryWrapper.where(ShopInfoTableDef.SHOP_INFO.STATE.eq(1));
        ShopInfo oShopInfo = oShopInfoMapper.selectOneByQuery(queryWrapper);
        if(oShopInfo == null){
            return Result.error("店铺不存在");
        }
        //获取用户在此店铺的订单
        queryWrapper = new QueryWrapper();
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.USER_ID.eq(oShopInfoDto.getUserId()));
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.SHOP_ID.eq(oShopInfoDto.getId()));
        return Result.ok(oOrderTakeawayMapper.selectCountByQuery(queryWrapper));
    }

    /**
     * 获取店铺配送费和打包费
     * @param oShopInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getShopInfoDeliveryPacking(ShopInfoDto oShopInfoDto) throws Exception {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ShopInfoTableDef.SHOP_INFO.ID.eq(oShopInfoDto.getId()));
        queryWrapper.where(ShopInfoTableDef.SHOP_INFO.STATE.eq(1));
        ShopInfo oShopInfo = oShopInfoMapper.selectOneByQuery(queryWrapper);
        if(oShopInfo == null){
            return Result.error("店铺不存在");
        }
        if(oShopInfo.getDeliveryPrice() == null){
            oShopInfo.setDeliveryPrice(Double.valueOf(ComVariableUtil.getSystemValue("delivery_price")));
        }
        if(oShopInfo.getPackingCharge() == null){
            oShopInfo.setPackingCharge(Double.valueOf(ComVariableUtil.getSystemValue("packing_charge")));
        }
        return Result.ok(oShopInfo);
    }

    /**
     * 获取推荐店铺（客户）
     * @param oShopInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getRecommendShopInfoUser(ShopInfoDto oShopInfoDto) throws Exception {
        QueryWrapper queryWrapper = new QueryWrapper();
        //判断是否传入校园ID
        if(StringUtils.isNotBlank(oShopInfoDto.getSchoolId())){
            queryWrapper.where(ShopInfoTable.SHOP_INFO.SCHOOL_ID.eq(oShopInfoDto.getSchoolId()));
        }
        queryWrapper.where(ShopInfoTableDef.SHOP_INFO.IS_RECOMMEND.eq(1));
        queryWrapper.where(ShopInfoTable.SHOP_INFO.STATE.eq(1));
        queryWrapper.where(ShopInfoTable.SHOP_INFO.EXAMINE_STATE.eq(1));
        queryWrapper.where(ShopInfoTable.SHOP_INFO.IS_PERFECT.eq(1));
        List<ShopInfo> oShopInfoList = oShopInfoMapper.selectListWithRelationsByQuery(queryWrapper);
        return Result.ok(oShopInfoList,oShopInfoList.size());
    }

}
